<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录记录 - 后台管理</title>
    <link rel="stylesheet" href="/static/base.css">
    <link rel="stylesheet" href="/static/components.css">
    <link rel="stylesheet" href="/static/pages.css">
    <link rel="stylesheet" href="/static/admin/admin.css">
    <script src="/static/lib/js/vue.global.js"></script>
    <script src="/static/lib/js/axios.min.js"></script>
</head>
<body>
  <div class="admin-layout">
    <!-- 顶部导航 -->
    <div class="admin-header">
      <h2>登录记录</h2>
      <div>
        <button class="btn" onclick="location.href='/'">返回前台</button>
        <button class="btn" onclick="logout()">退出</button>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="admin-main">
      <!-- 左侧导航（公共组件注入） -->
      <div class="admin-sidebar"></div>

      <!-- 右侧内容区域 -->
      <div class="admin-content">
        <div class="content-page active" id="app">
          <h3>登录记录</h3>
          <p class="page-description">查看用户登录和退出记录，包括登录时间、IP地址、用户代理等信息</p>

          <!-- 统计卡片 -->
          <div class="stats-grid">
            <div class="stat-card">
              <div class="stat-icon">📊</div>
              <div class="stat-content">
                <div class="stat-number" id="totalRecords">-</div>
                <div class="stat-label">总记录数</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">📅</div>
              <div class="stat-content">
                <div class="stat-number" id="todayRecords">-</div>
                <div class="stat-label">今日记录</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">👥</div>
              <div class="stat-content">
                <div class="stat-number" id="activeUsers">-</div>
                <div class="stat-label">活跃用户</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">🟢</div>
              <div class="stat-content">
                <div class="stat-number" id="onlineUsers">-</div>
                <div class="stat-label">在线用户</div>
              </div>
            </div>
          </div>

          <!-- 搜索和筛选区域 -->
          <div class="search-box">
            <div class="search-header">
              <h4>筛选条件</h4>
              <button @click="resetSearch" class="btn btn-sm">重置筛选</button>
            </div>
            <div class="search-filters">
              <div class="filter-group">
                <label>手机号搜索:</label>
                <input type="text" v-model="searchPhone" @input="searchRecords" placeholder="输入手机号..." class="search-input">
              </div>
              <div class="filter-group">
                <label>日期范围:</label>
                <div class="date-range">
                  <input type="date" v-model="startDate" @change="searchRecords" class="date-input">
                  <span class="date-separator">至</span>
                  <input type="date" v-model="endDate" @change="searchRecords" class="date-input">
                </div>
              </div>
              <div class="filter-group">
                <label>操作类型:</label>
                <select v-model="statusFilter" @change="searchRecords" class="select-input">
                  <option value="">全部类型</option>
                  <option value="login">登录</option>
                  <option value="logout">退出</option>
                </select>
              </div>
            </div>
          </div>

          <!-- 登录记录表格 -->
          <div class="performance-table">
            <table>
              <thead>
                <tr>
                  <th>ID</th>
                  <th>手机号</th>
                  <th>操作类型</th>
                  <th>操作时间</th>
                  <th>IP地址</th>
                  <th>用户代理</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="loading">
                  <td colspan="6" class="text-center">加载中...</td>
                </tr>
                <tr v-if="!loading && records.length === 0">
                  <td colspan="6" class="text-center">暂无登录记录</td>
                </tr>
                <tr v-for="record in records" :key="record.id">
                  <td>{{ record.id }}</td>
                  <td>{{ record.phone }}</td>
                  <td>
                    <span :class="record.status === 'login' ? 'status-login' : 'status-logout'">
                      {{ record.status === 'login' ? '登录' : '退出' }}
                    </span>
                  </td>
                  <td>{{ formatDateTime(record.operation_time) }}</td>
                  <td>{{ record.ip_address || '-' }}</td>
                  <td>{{ truncateUserAgent(record.user_agent) }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 分页 -->
          <div class="pagination" v-if="totalPages > 1">
            <button @click="changePage(currentPage - 1)" :disabled="currentPage <= 1" class="btn">上一页</button>
            <span style="margin: 0 10px;">第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
            <button @click="changePage(currentPage + 1)" :disabled="currentPage >= totalPages" class="btn">下一页</button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <style>
     .stats-grid {
       display: grid;
       grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
       gap: 20px;
       margin-bottom: 20px;
     }
     
     .stat-card {
       background: white;
       padding: 20px;
       border-radius: 8px;
       box-shadow: 0 2px 4px rgba(0,0,0,0.1);
       display: flex;
       align-items: center;
       gap: 15px;
     }
     
     .stat-icon {
       font-size: 32px;
       color: #3498db;
     }
     
     .stat-content {
       flex: 1;
     }
     
     .stat-number {
       font-size: 24px;
       font-weight: bold;
       color: #2c3e50;
       margin-bottom: 5px;
     }
     
     .stat-label {
       color: #6c757d;
       font-size: 14px;
     }
     
     .search-box {
       background: white;
       padding: 20px;
       border-radius: 8px;
       box-shadow: 0 2px 4px rgba(0,0,0,0.1);
       margin-bottom: 20px;
     }
     
     .search-header {
       display: flex;
       justify-content: space-between;
       align-items: center;
       margin-bottom: 15px;
     }
 
     .search-header h4 {
       margin: 0;
       color: #333;
     }
     
    /* 筛选区使用响应式网格布局 */
    .search-filters {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
      gap: 12px 16px;
      align-items: center;
    }

    /* 每个筛选项：左侧标签固定宽度，右侧控件自适应 */
    .filter-group {
      display: grid;
      grid-template-columns: 86px 1fr;
      align-items: center;
      gap: 8px;
    }

    .filter-group label {
      font-size: 14px;
      color: #555;
      font-weight: 500;
    }
    
    .search-input, .date-input, .select-input {
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
      width: 100%;
      box-sizing: border-box;
    }
    
    .search-input { max-width: 100%; }
    .date-input { max-width: 100%; }
    .select-input { max-width: 100%; }

    .date-range {
      display: grid;
      grid-template-columns: 1fr 18px 1fr;
      align-items: center;
      gap: 6px;
    }

    .date-separator {
      font-size: 14px;
      color: #555;
      }
     
     .performance-table {
       background: white;
       border-radius: 8px;
       box-shadow: 0 2px 4px rgba(0,0,0,0.1);
       overflow: hidden;
       margin-bottom: 20px;
     }
     
     .performance-table table {
       width: 100%;
       border-collapse: collapse;
     }
     
     .performance-table th,
     .performance-table td {
       padding: 12px;
       text-align: left;
       border-bottom: 1px solid #eee;
     }
     
     .performance-table th {
       background: #f8f9fa;
       font-weight: 600;
       color: #495057;
     }
     
     .performance-table tr:hover {
       background: #f8f9fa;
     }
     
     .status-login {
       background: #d4edda;
       color: #155724;
       padding: 4px 8px;
       border-radius: 4px;
       font-size: 12px;
     }
     
     .status-logout {
       background: #f8d7da;
       color: #721c24;
       padding: 4px 8px;
       border-radius: 4px;
       font-size: 12px;
     }
     
     .pagination {
       text-align: center;
       margin-top: 20px;
     }

    /* 小屏优化：标签与控件垂直排列 */
    @media (max-width: 520px) {
      .filter-group {
        grid-template-columns: 1fr;
      }
      .date-range {
        grid-template-columns: 1fr;
        gap: 8px;
      }
      .date-separator { display: none; }
    }
  </style>

  <script src="/static/admin/components/sidebar.js"></script>
  <script>
    const { createApp } = Vue;
    createApp({
      data() {
        return {
          records: [],
          currentPage: 1,
          pageSize: 20,
          totalPages: 1,
          searchPhone: '',
          startDate: '',
          endDate: '',
          statusFilter: '',
          loading: false
        }
      },
      mounted() {
        this.loadStats();
        this.loadRecords();
        // 注入公共侧边栏
        injectAdminSidebar('/admin/user/login-records');
      },
      methods: {
        async loadStats() {
          try {
            const response = await axios.get('/admin/api/user/login-stats');
            if (response.data.success) {
              document.getElementById('totalRecords').textContent = response.data.totalRecords || 0;
              document.getElementById('todayRecords').textContent = response.data.todayRecords || 0;
              document.getElementById('activeUsers').textContent = response.data.activeUsers || 0;
              document.getElementById('onlineUsers').textContent = response.data.onlineUsers || 0;
            }
          } catch (error) {
            console.error('加载统计数据失败:', error);
          }
        },
        async loadRecords() {
          this.loading = true;
          try {
            const params = {
              page: this.currentPage,
              size: this.pageSize,
              phone: this.searchPhone,
              start_date: this.startDate,
              end_date: this.endDate,
              status: this.statusFilter
            };
            const response = await axios.get('/admin/api/user/login-records', { params });
            if (response.data.success) {
              this.records = response.data.records;
              this.totalPages = Math.ceil(response.data.total / this.pageSize);
            }
          } catch (error) {
            console.error('加载登录记录失败:', error);
          } finally {
            this.loading = false;
          }
        },
        searchRecords() {
          this.currentPage = 1;
          this.loadRecords();
        },
        resetSearch() {
          this.searchPhone = '';
          this.startDate = '';
          this.endDate = '';
          this.statusFilter = '';
          this.currentPage = 1;
          this.loadRecords();
        },
        changePage(page) {
          this.currentPage = page;
          this.loadRecords();
        },
        formatDateTime(dateString) {
          if (!dateString) return '-';
          const date = new Date(dateString);
          return date.toLocaleString('zh-CN');
        },
        truncateUserAgent(userAgent) {
          if (!userAgent) return '-';
          return userAgent.length > 50 ? userAgent.substring(0, 50) + '...' : userAgent;
        },
        async logout() {
          try {
            await fetch('/admin/logout', { method: 'POST' });
            location.href = '/admin/login';
          } catch (e) {
            location.href = '/admin/login';
          }
        }
      }
    }).mount('#app');
  </script>
</body>
</html>
